package com.situ.b2c.register.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;

import com.situ.b2c.pojo.User;
import com.situ.b2c.register.service.UserService;
import com.situ.b2c.util.FileUploadUtil;
import com.situ.b2c.util.IOUtil;


@WebServlet("/UserDoUpdateServlet")
public class UserDoUpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		FileUploadUtil uploadUtil = new FileUploadUtil(request);
		
		String userName = uploadUtil.getParameter("userName");
		System.out.println(userName);
		String userPass = uploadUtil.getParameter("userNewPass");
		
		FileItem fileItem = uploadUtil.getBinaryData("userAvatar");
		StringBuffer avatarPath = null;
		if (fileItem != null) {
			InputStream inputStream = fileItem.getInputStream();
			String fileName = fileItem.getName();
			String realPath = request.getServletContext().getRealPath("/");
			avatarPath = new StringBuffer("uploadFiles/");
			avatarPath.append(Calendar.getInstance().getTimeInMillis()).append(fileName.substring(fileName.lastIndexOf(".")));
			File toFile = new File(realPath + avatarPath);
			IOUtil.readAndWriter(inputStream, toFile);
			
		}
		
		User user = new User();
		HttpSession session = request.getSession();
		User user1 = (User) session.getAttribute("login_user");
		user.setRowId(user1.getRowId());
		user.setUserCode(user1.getUserCode());
		user.setUserName(userName);
		user.setUserPass(userPass);
		user.setUserAvatar(avatarPath.toString());
		
		new UserService().update(user);
		response.sendRedirect("index.jsp");
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
